import httpFetch from 'share/httpFetch'
import config from 'config'
import errorMessage from "share/errorMessage"
import ExpenseChangeText from 'containers/my-account/components/expense-change-text'
import {Icon, message} from 'antd';
import { messages } from 'share/common';
import UnifiedTable from 'components/template/widget/unified-table/UnifiedTable'

export default {
    
  /**
   * 保存费用之前进行检查
   * @param expense
   * @return {AxiosPromise}
   */
  saveExpenseCheck(expense){
    return httpFetch.post(`${config.baseUrl}/invoice/api/invoicesSaveCheck`, expense);
  },

  /**
   * 保存 费用
   * @param expense
   * @return {AxiosPromise}
   */
  saveExpense(expense){
    //报销单费用
    // v3 统一费用保存接口
    return httpFetch.post(`${config.baseUrl}/invoice/api/v5/invoices`, expense);
  },

  /**
   * 滴滴打车消费记录生成费用
   * 注：当滴滴打车消费记录是多条的时候调用，单条滴滴打车消费记录使用/invoice/api/v5/invoices
   * @param {Array} params
   */
  saveDiDiExpense(params) {
    return httpFetch.post(`${config.baseUrl}/api/didiV3/addInvoice`, params);
  },

  /**
   * 得到车牌号列表
   */
  getCarNumberList(){
    //return httpFetch.get(`${config.baseUrl}/api/car`)
    return new Promise((resolve, reject) => {
      const res = httpFetch.get(`${config.baseUrl}/api/car?page=0&size=30`).then((res) => {
        resolve(res);
      }).catch((err) => {
        errorMessage(err.response);
        reject(err.response);
      });
    });
  },

  //单笔删除费用
  deleteExpense(invoiceOID, isConfirm){
    let params = {};
    isConfirm && (params.confirm = 'Y');
    return httpFetch.delete(`${config.baseUrl}/api/v2/invoice/${invoiceOID}`, params)
  },

  /**
   * 得到发票类型列表
   */
  getInvoiceTypeList(){
    return httpFetch.get(`${config.baseUrl}/api/custom/enumeration/receipt/type`)
  },

  /**
   * 得到可查验发票类型列表
   */
  getTestInvoiceTypeList(){
    return httpFetch.get(`${config.baseUrl}/api/invoice/invoiceType`)
  },

  /**
   * 根据发票类型得到税率
   * @param type
   */
  getRateByInvoiceType(type){
    return httpFetch.get(`${config.baseUrl}/api/custom/enumeration/tax/rate?receiptValue=${type}`)
  },

  /**
   * 发票查验
   * @param invoiceInfo 发票详情
   * @param userOID 报销单申请人OID
   * @param type 财务直接录入发票时的来源，发票袋或财务审核录入
   * @param id 财务直接录入发票时的发票袋id或报销单id
   * @return {AxiosPromise | *}
   */
  testInvoice(invoiceInfo, userOID, type, id){
    let params = { invoiceInfo };
    userOID && (params.userOID = userOID);
    // let url = '/api/receipt/verify/batch';
    let url = '/api/receipt/verify';
    console.log('22222222')
    if(type) {
      url = '/api/receipt/finance/verify';
      params.entityId = id;
      params.entityType = type;
    }
    if (url === '/api/receipt/verify/batch') {
      params = [params]
    }
    return httpFetch.post(`${config.receiptUrl}${url}`, params)
  },

  getBusinessCardStatus(userOID) {
    let params = { userOID };
    return httpFetch.get(`${config.baseUrl}/api/bankcard/user/status/CMBC`, params)
  },

  getTitleList(userOID){
    return httpFetch.get(`${config.baseUrl}/api/receipt/check/enable`, { userOID })
  },

  getExpenseList(page, size, expenseTypeIds,agentOid) {
    let params = {page, size, expenseTypeIds,applicantOID:agentOid};
    return httpFetch.post(`${config.baseUrl}/api/invoices/my`, params)
      .catch(e => {
        message.error(messages('common.error1')/*获取数据失败，请稍后重试或联系管理员*/);
        throw e;
      })
  },
  // 打印支付宝发票
  printAlipayInvoice(invoice) {
    let params = {
      userId: invoice.openid,
      invoiceCode: invoice.billingCode,
      invoiceNo: invoice.billingNo
    };
    return httpFetch.get(`${config.baseUrl}/api/invoice/alipay/pdf`, params, {}, {responseType: 'arraybuffer'});
  },
  //打印微信发票
  printInvoice(id){
    return httpFetch.get(`${config.receiptUrl}/api/receipt/pdf/${id}`);
  },

  //修改核定金额
  editAuditAmount(params){
    return httpFetch.post(`${config.baseUrl}/api/v2/invoices/review/amount`, params)
  },

  //财务修改录入发票内容
  editAuditInvoice(params){
    return httpFetch.post(`${config.baseUrl}/api/update/invoice/tax/rate`, params)
  },

  //财务补录发票信息
  financialAuditInvoice(params, type, id){
    let url = '/receipt/api/receipt/supplement';
    if(type) {
      params.entityId = id;
      params.entityType = type;
      url = '/api/expense/reports/bag/receipt/save';
    }
    return httpFetch.post(`${config.baseUrl}${url}`, params)
  },


  //费用模板下载
  invoiceTemplateDown(templateId){
    return httpFetch.get(`${config.baseUrl}/api/expense/template/`+templateId, {}, {}, {responseType: 'arraybuffer'})
  },

  //费用模板上传
  invoiceTemplateUpload(formData,expenseReportOID,expenseTypeOID){
    return httpFetch.post(`${config.baseUrl}/api/expense/import`, formData, {"Content-type": 'multipart/form-data'})
  },

  //检查发票重复
  checkRepeatInvoice(receiptCode, receiptNo){
    return httpFetch.get(`${config.baseUrl}/api/receipt/duplicate/check`, {
      receiptCode,
      receiptNo
    })
  },

  //修改商务卡备注
  updateBusinessCardRemark(cardId, remark){
    return httpFetch.put(`${config.baseUrl}/api/bankcard/transaction/add/remark/${cardId}?remark=${remark}`)
  },

  //得到阶梯或者单价模式
  getMileageMode(){
    return httpFetch.get(`${config.baseUrl}/api/pcfp/mode`)
  },
  //获取发票控件灵活配置信息
  getReceiptDisplay(receiptCheckEnabled, invoiceType, tenantId, setOfBookId, companyID) {
    let params = [{"factorCode": "TENANT", "factorValue": tenantId}, {
      "factorCode": "SET_OF_BOOKS",
      "factorValue": setOfBookId
    }, {"factorCode": "COMPANY", "factorValue": companyID}, {
      "factorCode": "RECEIPT_CHECK_ENABLED",
      "factorValue": receiptCheckEnabled === true ? 'Y':'N'
    }, {"factorCode": "RECEIPT_TYPE", "factorValue": invoiceType}]
    return httpFetch.post(`${config.baseUrl}/config/api/config/hit/RECEIPT_DISPLAY_CONTROL?tenantId=${tenantId}`, params)
  },

  getSubsidy(params){
    return httpFetch.get(`${config.baseUrl}/api/expense/report/v2/subsidy/detail?invoiceOID=${params.invoiceOID}&page=${params.page}&size=${params.size}`)
  },
  //删除发票
  deleteReceipt(receiptId){
    return httpFetch.delete(`${config.baseUrl}/receipt/api/receipts/${receiptId}`)
  },

  //转交费用
  transferExpense(params) {
    return httpFetch.post(`${config.baseUrl}/invoice/api/invoices/transfer/to`, params)
  },
  /**
   * 费用是否可复制
   * @param params
   * @returns {*}
   */
  validateCopyInvoice (params) {
    return httpFetch.get(`${config.baseUrl}/invoice/api/copy/validate?invoiceOID=${params.invoiceOID}`)
  },

  //核定金额计算
  getOriginalApprovedVat(params){
    return httpFetch.post(`${config.baseUrl}/invoice/api/invoice/tax/amount/by/receipts`,params)
  },

  /**
   * 获取发票填写图片信息
   * @param typeNo 发票类型
   * @returns {*}
   */
  getReceiptTipImg(typeNo) {
    return httpFetch.get(`${config.baseUrl}/api/receipt/type/image/${typeNo}`)
  },
  /**
   * @desc 财务操作当前费用能否抵扣
   * @param params
   * @returns {*|AxiosPromise|void}
   */
  setVatInvoice(params){
    return httpFetch.post(`${config.baseUrl}/api/invoice/deduction/set`,params)
  },
  /**
   * @desc 财务操作当前费用能否抵扣
   * @param params
   * @returns {*|AxiosPromise|void}
   */
  editTextFields(params){
    return httpFetch.post(`${config.baseUrl}/invoice/api/update/text`,params)
  },
  /**
   * 只读模式下显示值（只需要处理时间类的显示值，其他直接显示showValue）
   * @param field
   * @param isWithTime
   * @param getAuditOperateAuth
   * @param expenseReport
   * @param nowExpense
   * @param skipApplication
   * @param changeFieldValue
   * @param expenseType
   */
  getFieldName(field = {}, isWithTime, getAuditOperateAuth, expenseReport, nowExpense, skipApplication, changeFieldValue, isSubsidyType, expenseType) {
    const { fieldType, value, messageKey, showValue, customEnumerationOID } = field;
    if (fieldType === 'ASSOCIATE_APPLICATION') { //关联申请单需要跳转
      return (
        <div>
          {value ? (
            <a onClick={() => skipApplication(value)}><Icon fieldType="link"/>&nbsp;{value}</a>
          ) : '-'}
        </div>
      );
    }
    if (messageKey === 'public.assembly') {
      const expenseTypeField = expenseType.fields.find(item => item.fieldOID === field.fieldOID)
      if (!expenseTypeField) return '-'
      return (
        <UnifiedTable 
          readonly
          formField={expenseTypeField.formField}
          value={field.value}
        >
        </UnifiedTable>
      )
    }
    if ((fieldType === 'TEXT' && messageKey === 'dateCombined') || fieldType === 'START_DATE_AND_END_DATE') {
      if (value && JSON.parse(value)) {
        let result = JSON.parse(value);
        let formatData = (isWithTime && isSubsidyType) ? 'yyyy-MM-dd hh:mm' : 'yyyy-MM-dd';
        return (
          <span style={{ fontSize: 12 }}>
            {new Date(result.startDate).format(formatData)}
            {` ~ `}
            {new Date(result.endDate).format(formatData)}
            {` `}
          </span>
        );
      } else {
        return '-';
      }
    }
    if (fieldType === 'DATE') {
      return value ? new Date(value).format('yyyy-MM-dd') : '-';
    }
    if (fieldType === 'MONTH') {
      return value ? new Date(value).format('yyyy-MM') : '-';
    }
    if (fieldType === 'DATETIME') {
      return value ? new Date(value).format('yyyy-MM-dd hh:mm:ss') : '-';
    }
    if (fieldType === 'TEXT' && getAuditOperateAuth && messageKey !== 'dateCombined' && !customEnumerationOID) {
      // if (messageKey === 'mcd.car') {
      //   return value && JSON.parse(value)[0].carNumber
      // }
      return <ExpenseChangeText readonly invoiceOID={nowExpense.invoiceOID} expenseReportOID={expenseReport.expenseReportOID} onChange={changeFieldValue} field={field}/>;
    }
    if (messageKey === 'mcd.car') {
      return value && JSON.parse(value)[0].carNumber
    }
    if (fieldType === 'BOOLEAN') {
      //接口返回String型的true和false
      return value === 'true' ? messages('common.yes') : messages('common.no')
    }
    return showValue || '-';
  },

  //OCR查验
  checkOCR(params) {
    return httpFetch.post(`${config.baseUrl}/receipt/api/receipt/ocr`, params)
  },

  //OFD查验
  checkOFD(params) {
    return httpFetch.post("/receipt/api/receipt/ofd", params);
  },


  //发票查验（批量）
  checkInvoiceBatch(params) {
    return httpFetch.post(`${config.baseUrl}/receipt/api/receipt/verify/batch`, params)
  },

  //根据发票获取费用默认值
  getDefaultValueByInvoice(expenseTypeId, receipts) {
    let params = { expenseTypeId, receipts };
    return httpFetch.post(`${config.baseUrl}/invoice/api/invoice/defaults`, params)
  },
  // 获取发票的修改记录
  getInvoiceChangeRecordV2(receipt) {
    return httpFetch.post(`/api/receipt/query/label/detail`, receipt);
  },
  // 查询帐套启用的基于报销单审核业务的凭证类型
  getCertificatePreviewTab(setOfBooksId, functionDefineEnum = 'EXP_REPORT') {
    let params = { setOfBooksId, functionDefineEnum };
    return httpFetch.get(`/ledger/api/journal/template/query/by/function/define`, params);
  },
  getCertificateList(params) {
    return httpFetch.post(`${config.baseUrl}/ledger/api/journal/preview`, params)
  },
  //查询是否启用核算平台，若未启用则不展示凭证预览
  getAccountFlag() {
    return httpFetch.get(`/api/open/ledger/is/enable`);
  },

  //获取发票总金额
  getReceiptTotalAmount(params) {
    return httpFetch.post(`/invoice/api/receipt/cal/total_amount?newFlag=true`, params)
  },

  exportPDF(invoiceOIDs) {
    return httpFetch.post(`${config.baseUrl}/api/invoices/export`, invoiceOIDs);
  },
  // 根据不同的入口获取不同的要去掉的费用类型(注：当type===2时，获取到的是要展示的费用类型)
  getFilterExpenseTypes(type) {
    return httpFetch.get(`${config.baseUrl}/api/billtype?type=${type}`);
  },
  getAgentList() {
    return httpFetch.get(`${config.baseUrl}/api/bill/proxy/query/my/principals?operationCode=3`);
  },

  // 文档1963 追加判断接口
  getInvoiceCheck(expenseTypeId, receipts) {
    let params = { expenseTypeId, receipts };
    return httpFetch.post(`${config.baseUrl}/invoice/api/invoice/check`, params)
  },

  // 获取不展示电子支付凭证的 值列表
  getNotShowFileList(customEnumerationOID) {
    return httpFetch.get(`${config.baseUrl}/api/custom/enumerations/${customEnumerationOID}/items/v2?page=0&size=100&roleType=TENANT`)
  },
};
